import {ChangeDetectorRef, Component, ViewChild} from '@angular/core';
import {Content, IonicPage, NavController, NavParams} from 'ionic-angular';
import {SideMenuService} from "../../services/common/side-menu.service";
import {TabsPage} from "../tabs/tabs";
import {MeProvider} from "../../providers/me/me.provider";
import {PerformanceType} from "../../model/enum/performance";
import {ThemeBrowserService} from "../../services/native/theme-browser/theme-browser.service";
import {PerformanceProvider} from "../../providers/perfomance/performance/performance";
import {TimeUtil} from "../../model/util/TimeUtil";
import {LoadingService} from "../../services/common/loading.service";
import {AuthService} from "../../services/common/auth.service";
import {ToastService} from "../../services/common/toast.service";
import {CommissionPage} from "./commission/commission";
import {FileService} from "../../services/native/file/file.service";
import {CacheImgService} from "../../services/native/cache-img/cache-img.service";

@IonicPage()
@Component({
    selector: 'page-me',
    templateUrl: 'me.html',
    providers: [
        SideMenuService,
        MeProvider,
        ThemeBrowserService,
        PerformanceProvider,
        LoadingService,
        AuthService,
        FileService,
        ToastService
    ]
})
export class MePage {

    private personalInfo = {
        'directGroupID': null,
        'hrefMDRT': null,
        'monthTotalAPE': null,
        'monthTotalPC': null
    };
    private personalInfoToken = {
        'nickName': '',
        'profileURL': null,
        'agentLevel': '',
    };

    @ViewChild(Content) content: Content;

    isScrolled: boolean;

    constructor(public navCtrl: NavController, public navParams: NavParams,
                private sideMenuService: SideMenuService,
                public tabsPage: TabsPage,
                private meProvider: MeProvider,
                public changeRef: ChangeDetectorRef,
                public themeBrowserService: ThemeBrowserService,
                private performanceProvider: PerformanceProvider,
                public load: LoadingService,
                private fileService: FileService,
                private authService: AuthService,
                private toastService: ToastService,
                private cacheImg: CacheImgService) {

    }

    private authLevel;

    ionViewDidLoad() {
        this.authLevel = this.authService.getAuthLevel();
        // this.getBaseInfo();
        if (this.authLevel) {
            this.getPersonalInfo();
        }
    }

    ionViewDidEnter() {
        this.getBaseInfo();
    }

    openRoot = (name, index) => this.openTab(name, index);

    openMenu(myEvent) {
        this.sideMenuService.openSideMenu(myEvent)
    }

    openTab(name, index) {
        this.navCtrl.popToRoot();
        this.tabsPage.openPage({name: name, index: index});
    }

    getBaseInfo() {
        this.personalInfoToken.nickName = localStorage.getItem('nickName');
        let headImage = this.authService.getAuthAvator();
        this.fileService.getAzureInfo().subscribe((data) => {
            // this.personalInfoToken.profileURL = this.fileService.getCompletePath(headImage, data.azureInfo);
            this.cacheImg.getImgPath(headImage, data.azureInfo)
                .then((res) => {
                    this.personalInfoToken.profileURL = res;
                })
                .catch(err => {
                    console.log(err);
                });
        });
        this.personalInfoToken.agentLevel = localStorage.getItem('agentLevel');
    }

    /**
     * 下拉刷新
     */
    doRefresh(refresher) {

        this.getPersonalInfo(() => {
            refresher.complete();
        });
    }

    /**
     * 获取总览信息
     */
    getPersonalInfo(fun = null) {
        // this.performanceProvider.getAchievement('', TimeUtil.getLocalTime(Date.now()), TimeUtil.getLocalTime(Date.now()), PerformanceType.Person).subscribe(data => {
        //     this.personalInfo = data;
        //     this.load.dismissLoading(); sh57815
        // });

        this.load.showLoading();
        this.meProvider.getPersonalInfo().subscribe(res => {
            this.personalInfo = res;
            this.load.dismissLoading();
        }, error => {
            this.load.dismissLoading();
        });
        if (fun) fun();
    }

    settingClicked() {
        //测试跳转到手势密码
        this.navCtrl.push('SettingPage', {});
    }

    /**
     * 跳转至个人业绩详情
     */
    goPersonalPerformancePage() {
        this.navCtrl.push('PersonalGroupPerformancePage', {
            type: PerformanceType.Person
        })
    }

    /**
     * 跳转至直辖小组列表
     */
    goGroupPerformancePage() {
        this.navCtrl.push('GroupPerformanceListPage',
            {
                type: PerformanceType.Municipality
            })
    }

    /**
     * 跳转至所辖小组列表
     */
    goGroupPerformanceListPage() {
        this.navCtrl.push('GroupPerformanceListPage', {
            type: PerformanceType.Jurisdiction
        })
    }

    /**
     * ???????????
     */
    goHistoricalPerPage() {
        this.navCtrl.push('HistoricalPerformancePage');
    }


    /**
     *
     */
    contentScrolling() {
        const dimensions = this.content.getContentDimensions();
        this.isScrolled = dimensions.scrollTop > 80;
        this.changeRef.detectChanges();
    }

    /**
     * 打开外链MDRT
     * @param {string} url  外链URL，带上参数
     */
    openMDRT(url) {
        this.load.showLoading();
        this.meProvider.getMdrtLink().subscribe(data => {
            this.load.dismissLoading();
            if (data) {
                this.themeBrowserService.openBrowser(data)
            } else {
                this.toastService.showToast("请求失败，请重试。")
            }
        }, err => {
            this.load.dismissLoading();
        });
    }

    /**
     * 跳转到我的团队首页
     */
    goToMyteam() {
        this.navCtrl.push('TeamPerformanceOverviewPage')
    }

    /**
     * 跳转到我的佣金
     */
    goToCommission() {
        this.navCtrl.push('CommissionPage');
    }
}
